package view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.SystemColor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;

import model.Database;
import model.IOFile;
import model.OptionMessenger;
import model.UICommand;

import org.jdesktop.swingx.JXTextField;

import test.WrapLayout;

import com.alee.extended.image.WebImageDrop;
import com.alee.laf.WebLookAndFeel;
import com.alee.managers.language.data.TooltipWay;
import com.alee.managers.tooltip.TooltipManager;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import controller.ConfigureController;

import java.awt.Color;

public class ConfigurePanel extends JDialog {
	private static final long serialVersionUID = 391709869449247427L;
	private final JPanel contentPanel = new JPanel();
	private JPanel connect;
	private Database database, tmpDb;
	private JXTextField txtUser;
	private JPasswordField txtPass;
	private JXTextField txtHost;
	private JXTextField txtPort;
	private JXTextField txtDbName;
	private LogginPanel parentComponent;
	private JTabbedPane tabbedPane;
	private Image img;

	/**
	 * Create the dialog.
	 * 
	 */
	public ConfigurePanel(LogginPanel component, ConfigureController control) {
		this.parentComponent = component;
		try {
			this.database = Database.getInstance();
			this.tmpDb = Database.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace(IOFile.getInstance());
		}

		setModal(true);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
		setSize(504, 423);

		getContentPane().setLayout(new BorderLayout());

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		getContentPane().add(tabbedPane, BorderLayout.CENTER);
		tabbedPane.addTab("Kết nối", null, contentPanel);
		contentPanel.setLayout(new BorderLayout(0, 0));
		// {
		connect = new JPanel();
		connect.setBorder(new TitledBorder(null,
				"C\u00E0i \u0111\u1EB7t k\u1EBFt n\u1ED1i",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.textHighlight));
		contentPanel.add(connect, BorderLayout.CENTER);
		connect.setLayout(new FormLayout(new ColumnSpec[] { ColumnSpec
				.decode("default:grow"), }, new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, }));

		JLabel lblUser = new JLabel("Tên tài khoản truy cập cơ sở dữ liệu:");
		connect.add(lblUser, "1, 2, left, default");

		txtUser = new JXTextField();
		txtUser.setPrompt("Măc định là root");
		connect.add(txtUser, "1, 3, fill, default");

		JLabel lblMKhu = new JLabel("Mật khẩu truy cập cơ sở dữ liệu:");
		connect.add(lblMKhu, "1, 5, left, default");

		txtPass = new JPasswordField();
		connect.add(txtPass, "1, 6, fill, default");

		JLabel lblUrlhost = new JLabel("URL (host):");
		connect.add(lblUrlhost, "1, 8, left, default");

		txtHost = new JXTextField();
		txtHost.setPrompt("Mặc định localhost");
		connect.add(txtHost, "1, 9, fill, default");

		JLabel lblCngport = new JLabel("Cổng (port):");
		connect.add(lblCngport, "1, 11, left, default");

		txtPort = new JXTextField();
		txtPort.setPrompt("Mặc định 3306");
		connect.add(txtPort, "1, 12, fill, default");

		JLabel lblTnCsdl = new JLabel("Tên cơ sở dữ liệu:");
		connect.add(lblTnCsdl, "1, 14, left, default");

		txtDbName = new JXTextField();
		txtDbName.setPrompt("Mặc định storemanager");
		connect.add(txtDbName, "1, 15, fill, default");
		// }

		JPanel function = new JPanel();
		contentPanel.add(function, BorderLayout.SOUTH);
		function.setLayout(new GridLayout(0, 2, 0, 0));

		JButton btnCheck = new JButton("Kiểm tra kết nối");
		function.add(btnCheck);
		btnCheck.setActionCommand("check");
		btnCheck.addActionListener(control);

		JButton btnDefault = new JButton("Khôi phục mặc định");
		function.add(btnDefault);
		btnDefault.setActionCommand("default");
		btnDefault.addActionListener(control);

		JButton btnSave = new JButton("Lưu cấu hình");
		function.add(btnSave);
		btnSave.setActionCommand("save");
		btnSave.addActionListener(control);

		JButton btnBack = new JButton("Quay lại");
		function.add(btnBack);
		btnBack.setActionCommand(UICommand.BACK_CMD);
		btnBack.addActionListener(control);

		JPanel themePanel = new JPanel();
		tabbedPane.addTab("Giao diện", null, themePanel);
		themePanel.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		themePanel.add(scrollPane, BorderLayout.CENTER);

		WrapLayout wl_panel_1 = new WrapLayout();
		wl_panel_1.setAlignment(FlowLayout.LEFT);
		JPanel panel_1 = new JPanel(wl_panel_1);
		panel_1.setBackground(Color.LIGHT_GRAY);
		scrollPane.setViewportView(panel_1);

		int size = 145;
		panel_1.add(createWebImageDrop("/images/backgrounds/bg1.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg2.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg3.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg4.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg5.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg6.jpg", size,
				control));
		panel_1.add(createWebImageDrop("/images/backgrounds/bg0.jpg", size,
				control));

		JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		themePanel.add(panel, BorderLayout.SOUTH);

		JButton btnDuytnh = new JButton("Duyệt ảnh");
		btnDuytnh.setActionCommand(UICommand.SHOW_CMD);
		btnDuytnh.addActionListener(control);
		panel.add(btnDuytnh);

		JButton btnThot = new JButton("Thoát");
		btnThot.setActionCommand(UICommand.BACK_CMD);
		btnThot.addActionListener(control);
		panel.add(btnThot);

		if (database != null)
			getInforDatabase();

		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setLocationRelativeTo(component);
	}

	private WebImageDrop createWebImageDrop(String img, int size,
			ConfigureController control) {
		WebImageDrop webImageDrop = new WebImageDrop(size, size);
		TooltipManager.setTooltip(webImageDrop, "Nhấn đúp chuột để chọn",
				TooltipWay.up, 0);
		webImageDrop.addMouseMotionListener(control);
		webImageDrop.addMouseListener(control);
		try {
			webImageDrop.setImage(ImageIO.read(getClass().getResource(img)));
		} catch (IllegalArgumentException e) {
			e.printStackTrace(IOFile.getInstance());
		} catch (IOException e) {
			e.printStackTrace(IOFile.getInstance());
		}
		return webImageDrop;
	}

	public boolean checkConnection() {
		try {
			if (!setInforDatabase())
				OptionMessenger.showMessageDialog(this,
						"Chưa nhập tên database", "Lỗi",
						OptionMessenger.ERROR_MESSAGE);
			else {
				tmpDb.getConnection();
				OptionMessenger.showMessageDialog(this, "Kết nối thành công",
						"Thông báo", OptionMessenger.INFORMATION_MESSAGE);
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace(IOFile.getInstance());
			OptionMessenger.showMessageDialog(this,
					"Kết nối không thành công\nLỗi: " + e.getMessage(),
					"Thông báo", OptionMessenger.ERROR_MESSAGE);
		}
		return false;
	}

	public void saveConnection() {
		try {
			setInforDatabase();
			database.saveDatabaseObj();
			setVisible(false);
			OptionMessenger.showMessageDialog(
					OptionMessenger.windowForComponent(this),
					"Lưu cài đặt thành công", "Thông báo",
					OptionMessenger.INFORMATION_MESSAGE);
		} catch (FileNotFoundException e) {
			e.printStackTrace(IOFile.getInstance());
			OptionMessenger.showMessageDialog(this,
					"Không tìm thấy file: " + e.getMessage(), "Thông báo",
					OptionMessenger.ERROR_MESSAGE);
		} catch (IOException e) {
			e.printStackTrace(IOFile.getInstance());
			OptionMessenger.showMessageDialog(this,
					"Lỗi nhập xuất: " + e.getMessage(), "Thông báo",
					OptionMessenger.ERROR_MESSAGE);
		}
	}

	public boolean setInforDatabase() {
		if (!txtDbName.getText().equals("")) {
			tmpDb.setUserName(txtUser.getText());
			tmpDb.setPassword(new String(txtPass.getPassword()));
			tmpDb.setHost(txtHost.getText());
			tmpDb.setPort(txtPort.getText());
			tmpDb.setDbName(txtDbName.getText());

			return true;
		}
		return false;
	}

	public void getInforDatabase() {
		txtUser.setText(database.getUserName());
		txtPass.setText(database.getPassword());
		txtHost.setText(database.getHost());
		txtPort.setText(database.getPort());
		txtDbName.setText(database.getDbName());
	}

	public void setDatabase(Database db) {
		this.database = db;
	}

	@Override
	public void setVisible(boolean b) {
		setLocationRelativeTo(parentComponent);
		super.setVisible(b);
	}

	public static void main(String[] args) {
		WebLookAndFeel.install();
		new ConfigureController(null);
	}

	public boolean isShowingConfig() {
		return (tabbedPane.getSelectedIndex() == 0);
	}

	public void setImg(Image img) {
		this.img = img;
	}

	public void changeBackground() {
		parentComponent.setBackground(img);
		parentComponent.repaint();
	}

}
